import org.omg.PortableInterceptor.INACTIVE;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Stack;

public class No006 {
    /**
     * 输入一个链表，按链表从尾到头的顺序返回一个ArrayList。
     */
    public static void main(String[] args) {
        int[] arr = {3, 4, 1, 2, 3, 4, 5};
        ListNode listNode = create(arr);
        System.out.println(listNode);
        ArrayList<Integer> list = printListFromTailToHead(listNode);
        System.out.println(list);
    }

    public static ListNode create(int[] arr) {
        if (arr.length == 0) {
            return null;
        }
        ListNode listNode = new ListNode(arr[0]);
        listNode.next = create(Arrays.copyOfRange(arr, 1, arr.length));
        return listNode;
    }

    public static class ListNode {
        int val;
        ListNode next;

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }

        ListNode(int val) {
            this.val = val;
        }
    }

    //前插
    public static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        LinkedList<Integer> list = new LinkedList<>();
        ListNode tmp = listNode;
        while (tmp != null) {
            list.addFirst(tmp.val);
            tmp = tmp.next;
        }
        return new ArrayList<>(list);
    }

    //递归
    ArrayList<Integer> list = new ArrayList<>();

    public ArrayList<Integer> printListFromTailToHead2(ListNode listNode) {
        if (listNode != null) {
            printListFromTailToHead(listNode.next);
            list.add(listNode.val);
        }
        return list;
    }

    //栈
    public static ArrayList<Integer> printListFromTailToHead3(ListNode listNode) {
        Stack<Integer> s = new Stack<>();
        while (listNode != null) {
            s.push(listNode.val);
            listNode = listNode.next;
        }
        ArrayList<Integer> list = new ArrayList<>();
        while (!s.isEmpty()) {
            list.add(s.pop());
        }
        return list;
    }


}
